package xyz.kuailemao.mvc.interceptor;

import entity.Admin;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xyz.kuailemao.constant.CrowdConstant;
import xyz.kuailemao.exception.AccessForbiddenException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 创建时间：2022/8/17 8:18
 * 拦截器类
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.通过 request 对象获取 Session 对象
        HttpSession session = request.getSession();

        // 2.尝试从 Session 域中获取 Admin 对象
        Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);

        // 3.判断 admin 对象是否为空
        if (admin == null) {

            // 4.抛出异常
            throw new AccessForbiddenException(CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);
        }
        // 5.如果 admin 对象不为 null，则返回 true 放行
        return true;
    }
}
